package com.acoreful.ackitcloud.route.properties;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Data
@ConfigurationProperties(prefix = DynamicRouteConfigProperties.PREFIX)
@RefreshScope
public class DynamicRouteConfigProperties {

    private static final Logger log = LoggerFactory.getLogger(DynamicRouteConfigProperties.class);
    public static final String PREFIX = "gateway.route.config";

    private String dataId="gateway-routes.yaml";

    private String group;
    private String namespace;
    private String serverAddr;
    private String username;
    private String password;

    private Long timeout=5000L;

    @Autowired
    @JsonIgnore
    private Environment environment;

    @PostConstruct
    public void init() {
        this.overrideFromEnv();
    }

    private void overrideFromEnv() {
        if (environment == null) {
            return;
        }
        if (StringUtils.isEmpty(this.getServerAddr())) {
            String serverAddr = environment
                    .resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}");
            if (StringUtils.isEmpty(serverAddr)) {
                serverAddr = environment.resolvePlaceholders(
                        "${spring.cloud.nacos.server-addr:127.0.0.1:8848}");
            }
            this.setServerAddr(serverAddr);
        }
        if (StringUtils.isEmpty(this.getUsername())) {
            this.setUsername(
                    environment.resolvePlaceholders("${spring.cloud.nacos.username:}"));
        }
        if (StringUtils.isEmpty(this.getPassword())) {
            this.setPassword(
                    environment.resolvePlaceholders("${spring.cloud.nacos.password:}"));
        }
        if (StringUtils.isEmpty(this.getNamespace())) {
            this.setNamespace(
                    environment.resolvePlaceholders("${spring.cloud.nacos.config.namespace:}"));
        }
        if (StringUtils.isEmpty(this.getGroup())) {
            this.setGroup(
                    environment.resolvePlaceholders("${spring.cloud.nacos.config.group:}"));
        }
    }
}
